import { useState, useRef, useEffect } from "react";
import { useDashboardStore } from "@/store/price";
import Maycard from "@/components/may-card";
// import Dialogcard from "./Dialogcard";
import Dialogcard from "./New_dialogcard";
import ExceptionDialog from "./ExceptionDialog";

import Echartstabs from "./Echartstabs";

import mascot from "@/assets/mascot.png";
import card_bgc from "@/assets/imgs/card_bgc.png";
import announcement from "@/assets/imgs/announcement.png";
import guarantee from "@/assets/imgs/guarantee.png";
import record from "@/assets/imgs/record.png";
import tobedone from "@/assets/imgs/tobedone.png";
import { useNavigate } from "react-router";

import { DigitalEmployeerunData } from "@/api/Employee";
import { usetypesListtotalStore } from "@/store/leftcard";

import { Badge } from "antd";

const Leftcard = () => {
  const navigate = useNavigate();
  const [showMask, setShowMask] = useState(false);
  const [isClosing, setIsClosing] = useState(false);
  const [isechartstabs, setIsechartstabs] = useState(false);
  const [origin, setOrigin] = useState("center center");

  const [runcount, setRuncount] = useState(0);
  const [digtals, setDigtals] = useState(0);

  const [showExceptionDialog, setShowExceptionDialog] = useState(false);

  const imgRef = useRef<HTMLImageElement>(null);

  const {
    jobPersonnel: { value: personnel },
    workSchedule,
    scheduleRecord,
    cut_checkurl,
    weekreporturl,
  } = useDashboardStore();

  const { dutyOfficer, majorCorePosition, majorAccessPosition } = personnel;
  const { total } = usetypesListtotalStore();

  const gridlist = [
    {
      title: "异常记录",
      icon: record,
      action: () => setShowExceptionDialog(true),
      number: total,
    },
    {
      title: "数据分析",
      icon: tobedone,
      action: () => {
        setIsechartstabs(true);
      },
      number: 0,
    },
    {
      title: "网络运行周报",
      icon: guarantee,
      action: () => openUrl(weekreporturl),
      number: 0,
    },
    {
      title: "冲突监测",
      icon: announcement,
      action: () => openUrl(cut_checkurl),
      number: 0,
    },
  ];

  const handleOpen = () => {
    if (imgRef.current) {
      const rect = imgRef.current.getBoundingClientRect();
      setOrigin(
        `${rect.left + rect.width / 2}px ${rect.top + rect.height / 2}px`
      );
    }
    setShowMask(true);
    setIsClosing(false);
  };

  const handleClose = () => {
    setIsClosing(true);
    setTimeout(() => setShowMask(false), 300);
  };

  const renderPersonnelRow = (label: string, list: string[]) => (
    <div className="flex items-center bg-[#E8F2FF] mb-2 text-[16px] pt-1 pb-1 pl-4 rounded-[8px]">
      <span className="text-[#999999]">{label}</span>
      {list.map((name, i) => (
        <span key={i} className="font-bold ml-2">
          {name}
        </span>
      ))}
    </div>
  );

  const openUrl = (url: string) => {
    if (url) window.open(url, "_blank");
  };

  const DigitalEmployeerunDataApi = async () => {
    const res = await DigitalEmployeerunData();
    setRuncount(res.data.run_count);
    setDigtals(res.data?.digtals || 0);
  };

  useEffect(() => {
    DigitalEmployeerunDataApi();
  }, []);

  return (
    <>
      <div className="h-full flex flex-col">
        {/* 顶部头像卡片 */}
        <Maycard className="!min-h-60">
          <div className="flex justify-between bg-[#e8f2ff] rounded-16">
            <img
              ref={imgRef}
              className="w-[195px] h-auto cursor-pointer"
              src={mascot}
              alt="吉祥物"
              onClick={handleOpen}
            />
            <div className="w-[132px] h-[190px] cursor-pointer bg-[#E3F1FF] rounded-[2px_20px_20px_20px] p-4 text-4">
              大家好，我是您的交互机器人
              <span className="text-[#236BFF] text-6 font-bold">小滨</span>
              。很高兴为您服务！
            </div>
          </div>
        </Maycard>

        {/* 当班员工信息 */}
        <Maycard className="my-5 max-h-[320px]" header="当班次员工排班情况">
          <div className="flex h-full flex-col justify-between">
            {renderPersonnelRow("值班长", dutyOfficer)}
            {renderPersonnelRow("大核心", majorCorePosition)}
            {renderPersonnelRow("大接入", majorAccessPosition)}

            <div className="grid grid-cols-2 gap-[20px] text-[16px] text-neutral-50">
              <div
                className="bg-blue-500 flex items-center justify-center h-10 rounded-8 cursor-pointer"
                onClick={() => openUrl(workSchedule)}
              >
                排班计划
              </div>
              <div
                className="bg-blue-500 flex items-center justify-center h-10 rounded-8 cursor-pointer"
                onClick={() => openUrl(scheduleRecord)}
              >
                排班记录
              </div>
            </div>
          </div>
        </Maycard>

        {/* 底部背景图 */}
        <div
          className="w-full min-h-25 bg-cover bg-center mb-5 rounded-[20px]
          hover:shadow-lg transition-all duration-300 cursor-pointer 
                 active:scale-95 relative"
          style={{ backgroundImage: `url(${card_bgc})` }}
          onClick={() => navigate("/employee")}
        >
          <div className="text-[16px] text-right absolute right-10 bottom-3">
            <div>
              在线数字员工
              <span className="text-[#236BFF] font-bold">{digtals}</span>人
            </div>
            <div>
              数字员工执行次数
              <span className="text-[#236BFF] font-bold">{runcount}</span>次
            </div>
          </div>
        </div>

        {/* 常用链接卡片 */}

        <Maycard header="常用工作链接">
          <div className="flex items-center justify-between">
            {gridlist.map((item, index) => (
              <Badge count={item.number}>
                <div
                  key={index}
                  className="flex flex-col items-center cursor-pointer"
                  onClick={item.action}
                >
                  <img className="w-13 h-13" src={item.icon} alt={item.title} />
                  <span className="text-[16px] whitespace-nowrap overflow-hidden text-ellipsis">
                    {item.title}
                  </span>
                </div>
              </Badge>
            ))}
          </div>
        </Maycard>
      </div>

      <ExceptionDialog
        open={showExceptionDialog}
        onClose={() => setShowExceptionDialog(false)}
      />

      <Echartstabs
        open={isechartstabs}
        onClose={() => setIsechartstabs(false)}
      />

      {/* 弹窗遮罩 */}
      {showMask && (
        <div
          onClick={handleClose}
          style={{ transformOrigin: origin }}
          className={`fixed top-0 pt-25 pr-[26%] pb-10 pl-10 left-0 w-full h-full bg-black/50 z-50 transform transition-transform duration-300 ${
            isClosing ? "scale-0" : "scale-100"
          }`}
        >
          <div className="w-full h-full" onClick={(e) => e.stopPropagation()}>
            <Dialogcard />
          </div>
        </div>
      )}
    </>
  );
};

export default Leftcard;
